package com.syxbbs.forum.services.Impl;

import com.syxbbs.forum.Utils.MD5Utils;
import com.syxbbs.forum.Utils.StringUtils;
import com.syxbbs.forum.Utils.UUID;
import com.syxbbs.forum.common.AppResult;
import com.syxbbs.forum.common.ResultCode;
import com.syxbbs.forum.dao.UserMapper;
import com.syxbbs.forum.exception.ApplicationException;
import com.syxbbs.forum.model.User;
import com.syxbbs.forum.services.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService  {

    @Autowired
    private UserMapper userMapper;
    /*注册
    * 1非空校验*/
    @Override
    public void createNormal(User user) {
        if(user==null|| StringUtils.isEmpty(user.getNickname()) || StringUtils.isEmpty(user.getUsername()) ||
                StringUtils.isEmpty(user.getPassword())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //统一抛出异常
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));


        }
        /*
         * 2按照用户名查找用户信息*/
        User exist = userMapper.selectByUserName(user.getUsername());
        //发现数据库中有相同username的元素，就抛出异常。
        if (exist!=null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //异常：用户已经存在。
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_EXISTS));

        }
        /*
        * 3.新增用户*/
        user.setArticleCount(0);
        user.setGender((byte) 2);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date=new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //写入数据库,这里查询发现没有姓名相同的用户，但是仍然新增失败。
        int raw = userMapper.insertSelective(user);
        if (raw!=1){
            //新增失败
            log.error(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(ResultCode.FAILED_CREATE.toString());

        }
        log.info(ResultCode.SUCCESS.toString()+"+++++++++++++"+user.getUsername());


    }

    //根据username查询内容(查询)。
    @Override
    public User selectByUserName(String username) {
        if(StringUtils.isEmpty(username)){
            log.error("未输入username");
            throw new ApplicationException("未输入username");
        }
        User user = userMapper.selectByUserName(username);
        if (user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());

        }
        return userMapper.selectByUserName(username);

    }

    @Override
    public User login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            log.info(ResultCode.FAILED_LOGIN.toString());
            //抛出异常，非空校验失败。
            throw new ApplicationException(ResultCode.FAILED_LOGIN.toString());

        }
        User user = userMapper.selectByUserName(username);
        if(user==null){
            //校验失败，日志打印异常的登录username。
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"username"+username);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());

        }
        //接下来是校验密码的环节
        String md5salt = MD5Utils.md5salt(password, user.getSalt());
        //校验失败的话
        if (!md5salt.equals(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //有全局异常处理
            throw new ApplicationException(ResultCode.FAILED_LOGIN.getMessage().toString());

        }
        //校验成功,返回用户信息。
        log.info("登入成功");
        return user;

    }

    @Override
    public User selectById(Long id) {
        if(id==null){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_LOGIN.toString());


        }
        //如果存在的话，调用Dao返回对象。
        User user = userMapper.selectByPrimaryKey(id);
        return user;


    }
    //更新帖子数量，将帖子数量加1.
   /* @Transactional*/
    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null || id<0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failure());
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failure("插入有错误"));


        }



    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null || id<0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
        }
        User user=userMapper.selectByPrimaryKey(id);
        if (user==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failure());
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if (user.getArticleCount()<0){
            user.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failure("插入有错误"));
        }





    }

    @Override
    public void modifyInfo(User user) {
        //什么都没有传入是不允许修改的
        Boolean checkArr=false;
        //非空校验
        if (user==null || user.getId()==null ||user.getId()<=0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());

        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        //用户不存在
        if (existsUser==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        //定义一个专门用来更新，防止用户设置过多属性,覆盖没有经过校验的字段，关于更新要重新设置对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        if (!StringUtils.isEmpty(user.getUsername()) && !user.getUsername().equals(existsUser.getUsername())){
            //查询登录名是否唯一
            User checkUser=userMapper.selectByUserName(user.getUsername());
            if (checkUser!=null){
                //用户已经存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(ResultCode.FAILED_USER_EXISTS.toString());
            }
            //没有找到,就可以修改
            updateUser.setUsername(user.getUsername());
            checkArr=true;
        }
        //校验昵称
        if (!StringUtils.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname()) ){
            //没有找到,就可以修改
            updateUser.setNickname(user.getNickname());
            checkArr=true;


        }
        if (user.getGender()!=null && existsUser.getGender()!=user.getGender()){
            //没有找到,就可以修改

            updateUser.setGender(user.getGender());
            if (user.getGender()<0 || user.getGender()>2){
                updateUser.setGender((byte) 2);
            }
            checkArr=true;


        }
        if (!StringUtils.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkArr=true;


        }
        if (!StringUtils.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkArr=true;
        }
        if (!StringUtils.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkArr=true;
        }
        if (checkArr==false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        int row = userMapper.updateByPrimaryKeySelective(user);
        if (row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(ResultCode.ERROR_SERVICES.toString());
        }



    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id==null || id<=0 || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null || user.getState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());


        }
        String oldEncryptPassword = MD5Utils.md5salt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(ResultCode.FAILED.toString());

        }
        String salt= UUID.UUID_32();
        String newEncryptPassword = MD5Utils.md5salt(newPassword, salt);
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        Date date=new Date();
        updateUser.setUpdateTime(date);



        updateUser.setPassword(newEncryptPassword);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+"受影响行数不为1");
            throw new ApplicationException(ResultCode.FAILED.toString());
        }




    }



}
